package com.kkd.kkdapp.activity;

import java.math.RoundingMode;
import java.text.DecimalFormat;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.DebtExchangeData;
import com.kkd.kkdapp.http.entity.DebtTransSuccessData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.view.HorScrollView;
import com.kkd.kkdapp.view.HorScrollView.OnScrollListener;
import com.kkd.kkdapp.view.XianduanView;

/**
 * 债权转让
 */
public class DebtExchangeActivity extends BaseActivity {

	private Context mContext = this;

	private final int SUC_REQUEST = 1001;
	private final int FAIL_REQUEST = 1002;
	private final int SUC_COMMIT = 2001;
	private final int FAIL_COMMIT = 2002;

	private View back;
	private HorScrollView horScroll;
	private XianduanView xianduanView;
	private TextView tv_xishu;
	private TextView bid_name;
	private TextView investment_amount;
	private TextView interest_rate;
	private TextView term;
	private TextView tv_daishoubenxi;
	private EditText input_fenshu;
	private TextView toAll;
	private TextView yv_zongjia;
	private TextView num_jiage;
	private TextView num_yuqizonge;
	private TextView num_yuqifuwufei;
	private TextView num_yuqishouru;
	private View next_bt;
	private View financial_agreement_ll;
	private DecimalFormat df;
	private DecimalFormat df2;
	private DecimalFormat df3;
	private DecimalFormat df_price;
	private DecimalFormat df_price_half_up;// 四舍五入
	private DecimalFormat df_money = new DecimalFormat("###,##0.00");
	private PopupWindow tip_popupWindow;
	private String bidId;
	private String poiId;
	private String bidTitle;
	private double currentValue;// 当前价值
	private long allowParts;// 可转让份数
	private double serviceFeeRatio;// 预期服务费比率
	private double xishu;// 转让系数
	private long curParts = 0;// 当前选择的份数
	private String docUrl;// 协议url
	private int factorStep;// 颗粒百分比 100--整数；10-小数点后1位；1--小数点后2位
	/**
	 * 当天持有天数
	 */
	private double curBillDate;
	/**
	 * 年利率
	 */
	private double preYearRate;
	/**
	 * 加息利率
	 */
	private double activityRate;
	/**
	 * 每份本金
	 */
	private double perPrincipal;
	/**
	 * 精确的当前价值
	 */
	private double currentValue_accurate;

	private Dialog loadDialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SUC_REQUEST:
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				DebtExchangeData data = (DebtExchangeData) msg.obj;
				if (data != null) {
					// 当天持有天数
					curBillDate = data.getCurBillDate();
					// 年利率
					preYearRate = data.getPreYearRate();
					// 加息利率
					activityRate = data.getActivityRate();
					// 每份本金
					perPrincipal = data.getPerPrincipal();
					// 精确的当前价值
					currentValue_accurate = (10000.0 * perPrincipal * 360
							+ 10000.0 * perPrincipal * curBillDate
							* preYearRate * 0.0001 + 10000.0 * perPrincipal
							* curBillDate * activityRate * 0.0001) / 360 * 0.000001;
					// 设置标题
					bidTitle = data.getBidTitle();
					bid_name.setText(bidTitle);
					// 可转让份数
					allowParts = data.getAllowParts();
					investment_amount.setText(allowParts + "份");
					input_fenshu.setHint("至多可转让" + allowParts + "份");
					// 当前价值
					currentValue = data.getCurrentValue() * 0.01;
					interest_rate.setText(df.format(currentValue) + "元/份");
					// 剩余期限
					term.setText(data.getRemainTerm());
					// 待收本息
					tv_daishoubenxi
							.setText(df.format(data.getWaitCollect() * 0.01)
									+ "元");
					// 预期服务费比率
					serviceFeeRatio = 1.00 * data.getServiceFeeRatio() / 10000;
					// 协议url
					docUrl = data.getDocUrl();
					// 颗粒百分比
					factorStep = data.getFactorStep();
					// 设置每段的百分比
					xianduanView.setPercent(1f * factorStep / 100);
					// 设置线段滚动到100%
					mHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							horScroll.scrollBy(xianduanView.get100(), 0);
						}
					}, 60);
				}
				break;

			case FAIL_REQUEST:
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				String desc = (String) msg.obj;
				AppUtil.makeToastForCustomer(mContext, desc);
				// 设置每段的百分比
				xianduanView.setPercent(1f);
				// 设置线段滚动到100%
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						horScroll.scrollBy(xianduanView.get100(), 0);
					}
				}, 60);
				break;

			case SUC_COMMIT:
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				DebtTransSuccessData data_suc = (DebtTransSuccessData) msg.obj;
				if (data_suc != null) {
					Intent intent = new Intent(mContext,
							DebtSuccessActivity.class);
					intent.putExtra("bidTitle", bidTitle);
					intent.putExtra("expectAmount",
							df_money.format(data_suc.getExpectAmount() * 0.01));
					intent.putExtra("expectPart", data_suc.getExpectPart() + "");
					intent.putExtra("transPrice",
							df_money.format(data_suc.getTransPrice() * 0.01));
					intent.putExtra("ratio",
							df.format(data_suc.getRatio() * 0.01));
					intent.putExtra("serviceFee",
							df_money.format(data_suc.getServiceFee() * 0.01));
					intent.putExtra("lastDate", data_suc.getLastDate());
					startActivity(intent);
					finish();
				}
				break;

			case FAIL_COMMIT:
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				String desc_commit = (String) msg.obj;
				AppUtil.makeToastForCustomer(mContext, desc_commit);
				break;

			default:
				break;
			}
		}
	};

	private View tip_dangqianjiazhi;

	private View tip_daishoubenxi;

	private View tip_zhuanrangxishu;

	private View tip_yuqizhuanrangzonge;

	private View tip_yuqifuwufei;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_debt_exchange);
		getMessage();
		initDF();
		initView();
		initListener();
		initXianduan();
		requestData();
	}

	private void getMessage() {
		Intent intent = getIntent();
		bidId = intent.getStringExtra("bidId");
		poiId = intent.getStringExtra("poiId");
	}

	/**
	 * 初始化格式化工具
	 */
	private void initDF() {
		df = new DecimalFormat("0.00");
		df2 = new DecimalFormat("0.0");
		df3 = new DecimalFormat("0");
		df_price = new DecimalFormat("0.00");
		df_price.setRoundingMode(RoundingMode.DOWN);
		df_price_half_up = new DecimalFormat("0.00");
		df_price_half_up.setRoundingMode(RoundingMode.HALF_UP);
	}

	private void initView() {
		// 返回键
		back = findViewById(R.id.condition_img);
		// 转让系数
		tv_xishu = (TextView) findViewById(R.id.tv_xishu);
		// 转让系数tip
		tip_zhuanrangxishu = findViewById(R.id.tip_zhuanrangxishu);
		// 线段的容器
		horScroll = (HorScrollView) findViewById(R.id.horScroll);
		// 线段
		xianduanView = (XianduanView) findViewById(R.id.xianduanView);
		// 标的名称
		bid_name = (TextView) findViewById(R.id.bid_name);
		// 可转让份数
		investment_amount = (TextView) findViewById(R.id.investment_amount);
		// 当前价值
		interest_rate = (TextView) findViewById(R.id.interest_rate);
		// 当前价值tip
		tip_dangqianjiazhi = findViewById(R.id.tip_dangqianjiazhi);
		// 剩余期限
		term = (TextView) findViewById(R.id.term);
		// 待收本息
		tv_daishoubenxi = (TextView) findViewById(R.id.tv_daishoubenxi);
		// 待收本息tip
		tip_daishoubenxi = findViewById(R.id.tip_daishoubenxi);
		// 转让份数
		input_fenshu = (EditText) findViewById(R.id.input_fenshu);
		// 全转
		toAll = (TextView) findViewById(R.id.toAll);
		// 折让总价
		yv_zongjia = (TextView) findViewById(R.id.yv_zongjia);
		// 转让价格
		num_jiage = (TextView) findViewById(R.id.num_jiage);
		// 预期转让总额
		num_yuqizonge = (TextView) findViewById(R.id.num_yuqizonge);
		// 预期转让总额tip
		tip_yuqizhuanrangzonge = findViewById(R.id.tip_yuqizhuanrangzonge);
		// 预期服务费
		num_yuqifuwufei = (TextView) findViewById(R.id.num_yuqifuwufei);
		// 预期服务费tip
		tip_yuqifuwufei = findViewById(R.id.tip_yuqifuwufei);
		// 预期收入
		num_yuqishouru = (TextView) findViewById(R.id.num_yuqishouru);
		// 确认转让
		next_bt = findViewById(R.id.next_bt);
		// 查看借款合同
		financial_agreement_ll = findViewById(R.id.financial_agreement_ll);
	}

	/**
	 * 初始化线段
	 */
	private void initXianduan() {
		// // 设置每段的百分比
		// xianduanView.setPercent(1f * factorStep / 100);
		// 添加滚动监听
		horScroll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(float percent) {
				// 转让系数
				if (factorStep > 50) {// 保留到整数
					tv_xishu.setText(df3.format(percent) + "%");
					xishu = Double.parseDouble(df3.format(percent)) / 100;
				} else if (factorStep == 50) {// 保留到小数点后一位
					tv_xishu.setText(df2.format(percent) + "%");
					xishu = Double.parseDouble(df2.format(percent)) / 100;
				} else if (factorStep < 50) {// 保留到小数点后两位
					tv_xishu.setText(df.format(percent) + "%");
					xishu = Double.parseDouble(df.format(percent)) / 100;
				}
				// 折让总价
				double allPrice = currentValue_accurate * curParts
						* ((1000.0 - xishu * 1000.0) / 1000.0);
				yv_zongjia.setText(df_price.format(allPrice) + "元");
				// 转让价格
				double transPrice = currentValue_accurate * xishu;
				num_jiage.setText(df_price.format(transPrice) + "元/份");
				double transPrice_last = Double.parseDouble(df_price
						.format(transPrice));
				// 预期转让总额
				double maybeAllPrice = transPrice_last * curParts;
				num_yuqizonge.setText(df_price.format(maybeAllPrice) + "元");
				double maybeAllPrice_last = Double.parseDouble(df_price
						.format(maybeAllPrice));
				// 预期服务费
				double maybeExtra = maybeAllPrice * serviceFeeRatio;
				num_yuqifuwufei.setText(df_price_half_up.format(maybeExtra)
						+ "元");
				double maybeExtra_last = Double.parseDouble(df_price_half_up
						.format(maybeExtra));
				// 预期收入
				double maybeIncome = maybeAllPrice_last - maybeExtra_last;
				num_yuqishouru.setText(df_price.format(maybeIncome) + "元");
			}
		}, xianduanView);
		// // 设置线段滚动到100%
		// mHandler.postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// horScroll.scrollBy(xianduanView.get100(), 0);
		// }
		// }, 60);
	}

	private void initListener() {
		// 返回键
		back.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				finish();
			}
		});
		// 全转
		toAll.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				if (allowParts > 0) {
					input_fenshu.setText(allowParts + "");
					String trim = input_fenshu.getText().toString().trim();
					if (!TextUtils.isEmpty(trim)) {
						input_fenshu.setSelection(trim.length());
					}
				}
			}
		});
		// 查看借款合同
		financial_agreement_ll.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				if (!TextUtils.isEmpty(docUrl)) {
					Intent intent = new Intent(mContext, KKDWebActivity.class);
					intent.putExtra("url", docUrl);
					startActivity(intent);
				}
			}
		});
		// 确认转让
		next_bt.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				if (!TextUtils
						.isEmpty(input_fenshu.getText().toString().trim())) {
					commitDebtExchange(poiId, curParts, xishu);
				} else {
					AppUtil.makeToastForCustomer(mContext, "请输入转让份数");
				}
			}
		});
		// 当前价值tip
		tip_dangqianjiazhi.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				showTipPopupwindow(v,
						"您本期实际持有天数预期享有的本息，不足月部分利息将由受让人承担，每笔成交后返还给您");
			}
		});
		// 待收本息tip
		tip_daishoubenxi.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				showTipPopupwindow(v, "为未还款的总待收本息");
			}
		});
		// 转让系数tip
		tip_zhuanrangxishu.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				showTipPopupwindow(v, "转让系数指转出债权本金的折扣率，范围90%-100%，作用于本金、利息部分");
			}
		});
		// 预期转让总额tip
		tip_yuqizhuanrangzonge.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				showTipPopupwindow(v,
						"实际成交金额的" + df.format(serviceFeeRatio * 100)
								+ "%，未交易部分不收取");
			}
		});
		// 预期服务费tip
		tip_yuqifuwufei.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				showTipPopupwindow(v,
						"实际成交金额的" + df.format(serviceFeeRatio * 100)
								+ "%，未交易部分不收取");
			}
		});
		// edittext
		input_fenshu.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				try {
					String curString = s.toString().trim();
					if (!TextUtils.isEmpty(curString)) {
						if ("0".equals(curString)) {
							input_fenshu.setText("");
							return;
						}
						curParts = Long.parseLong(curString);
						if (curParts > allowParts) {
							curParts = allowParts;
							input_fenshu.setText(allowParts + "");
							String trim = input_fenshu.getText().toString()
									.trim();
							if (!TextUtils.isEmpty(trim)) {
								input_fenshu.setSelection(trim.length());
							}
							if (allowParts > 0) {
								AppUtil.makeToastForCustomer(mContext,
										"已自动为您填入最大转让份数");
							}
							return;
						}
					} else {
						curParts = 0;
					}
					// 折让总价
					double allPrice = currentValue_accurate * curParts
							* ((1000.0 - xishu * 1000.0) / 1000.0);
					yv_zongjia.setText(df_price.format(allPrice) + "元");
					// 转让价格
					double transPrice = currentValue_accurate * xishu;
					num_jiage.setText(df_price.format(transPrice) + "元/份");
					double transPrice_last = Double.parseDouble(df_price
							.format(transPrice));
					// 预期转让总额
					double maybeAllPrice = transPrice_last * curParts;
					num_yuqizonge.setText(df_price.format(maybeAllPrice) + "元");
					double maybeAllPrice_last = Double.parseDouble(df_price
							.format(maybeAllPrice));
					// 预期服务费
					double maybeExtra = maybeAllPrice * serviceFeeRatio;
					num_yuqifuwufei.setText(df_price_half_up.format(maybeExtra)
							+ "元");
					double maybeExtra_last = Double
							.parseDouble(df_price_half_up.format(maybeExtra));
					// 预期收入
					double maybeIncome = maybeAllPrice_last - maybeExtra_last;
					num_yuqishouru.setText(df_price.format(maybeIncome) + "元");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 弹出气泡提示popupwindow
	 * 
	 * @param targetView
	 * @param desc
	 */
	private void showTipPopupwindow(View targetView, String desc) {
		if (tip_popupWindow != null) {
			tip_popupWindow.dismiss();
			tip_popupWindow = null;
		}
		tip_popupWindow = DialogUtils.showTipPopupWindow(mContext, targetView,
				desc);
	}

	/**
	 * 请求数据
	 */
	private void requestData() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(mContext, "加载中...");
		KkdHttpMagager.getInstance().getDebtExchange(poiId,
				DebtExchangeData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = Message.obtain();
						msg.what = SUC_REQUEST;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = FAIL_REQUEST;
						msg.obj = desc;
						msg.arg1 = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}

	/**
	 * 提交债权转让接口
	 */
	private void commitDebtExchange(String id, long parts, double ratio) {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(mContext, "加载中...");
		KkdHttpMagager.getInstance().getCommitDebtExchange(id, parts + "",
				(int) (ratio * 10000) + "", DebtTransSuccessData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = Message.obtain();
						msg.what = SUC_COMMIT;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = FAIL_COMMIT;
						msg.obj = desc;
						msg.arg1 = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
	}
}
